package com.jinlingxiu.app.mvp.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.widget.ImageView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.baidu.tts.client.SpeechSynthesizer
import com.baidu.tts.client.TtsMode
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jaeger.library.StatusBarUtil
import com.jinlingxiu.app.R
import com.jinlingxiu.app.mvp.contract.MainContract
import com.jinlingxiu.app.mvp.presenter.MainPresenter
import com.jinlingxiu.app.other.bean.ErrorBean
import com.jinlingxiu.app.other.bean.LinkedInitialBean
import com.jinlingxiu.app.other.ext.setNoDoubleClick
import com.jinlingxiu.app.other.interf.MySpeechSynthesizerListener
import com.jinlingxiu.app.other.widgets.LoadingDialogBehavior
import com.xdja.easymvp.base.BaseActivity
import com.xdja.easymvp.http.imageloader.glide.GlideArms
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast
import org.koin.android.ext.android.getKoin
import org.koin.androidx.scope.lifecycleScope

/**
 * 描述:  主页面答题
 * Create by yuanwanli
 * Date 2020/09/08
 */
class MainActivity : BaseActivity<MainPresenter>(), MainContract.View, MySpeechSynthesizerListener {
    override var mPresenter: MainPresenter? = lifecycleScope.get()
    lateinit var currentInitialBean: LinkedInitialBean
    private var mSpeechSynthesizer: SpeechSynthesizer? = SpeechSynthesizer.getInstance()
    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_main
    private val materialDialog: MaterialDialog by lazy {
        MaterialDialog(
            this,
            dialogBehavior = LoadingDialogBehavior()
        ).customView(R.layout.dialog_progress)
    }
    private val speechDialog: MaterialDialog by lazy {
        val dialog = MaterialDialog(
            this,
            dialogBehavior = LoadingDialogBehavior()
        )
        dialog.noAutoDismiss()
        dialog.cancelOnTouchOutside(false)
        dialog.customView(R.layout.dialog_voice)
        val recordImage = dialog.getCustomView().findViewById<ImageView>(R.id.ivRecord)
        GlideArms.with(this).asGif().load(R.drawable.voice_animation).into(recordImage)
        dialog
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initData(savedInstanceState: Bundle?) {
        StatusBarUtil.setTransparent(this)
        StatusBarUtil.setLightMode(this)
        initSpeechSdk()
        mPresenter?.getQuestion()
        //利用单链表实现更简单
        ivUp.setNoDoubleClick {
            val preInitialBean = currentInitialBean.preInitialBean
            if (preInitialBean == null) {
                ToastUtils.showShort("当前是第一题")
            } else {
                currentInitialBean = preInitialBean
                setCurrentData()
            }
        }
        ivLeft.setNoDoubleClick {
            if (currentInitialBean.soundPath.isEmpty()) {
                toast(getString(R.string.no_sound))
                return@setNoDoubleClick
            }
            val nextInitialBean = currentInitialBean.nextInitialBean
            currentInitialBean.correct = false
            if (nextInitialBean == null) {
                jumpNextPage()
            } else {
                currentInitialBean = nextInitialBean
                setCurrentData()
            }
        }
//        ivStart.setNoDoubleClick {
//            mSpeechSynthesizer?.stop()
//            mSpeechSynthesizer?.speak(tvTitle.text.toString())
//        }
        ivStart.setOnLongClickListener {
            setEnableClick(false)
            speechDialog.show()
            mPresenter?.recordVoice()
            true
        }
        ivStart.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                speechDialog.dismiss()
                mPresenter?.stopRecord()
                return@setOnTouchListener true
            }
            false
        }
        ivRight.setNoDoubleClick {
            if (currentInitialBean.soundPath.isEmpty()) {
                toast(getString(R.string.no_sound))
                return@setNoDoubleClick
            }
            val nextInitialBean = currentInitialBean.nextInitialBean
            currentInitialBean.correct = false
            if (nextInitialBean == null) {
                jumpNextPage()
            } else {
                currentInitialBean = nextInitialBean
                setCurrentData()
            }
        }
        ivDown.setNoDoubleClick {
//            if (currentInitialBean.soundPath.isEmpty()) {
//                toast(getString(R.string.no_sound))
//                return@setNoDoubleClick
//            }
            val nextInitialBean = currentInitialBean.nextInitialBean
            currentInitialBean.correct = true
            if (nextInitialBean == null) {
                jumpNextPage()
            } else {
                currentInitialBean = nextInitialBean
                setCurrentData()
            }
        }
    }

    private fun jumpNextPage() {
        var temp = currentInitialBean
        var errors = arrayListOf<ErrorBean>()
        while (temp.preInitialBean != null) {
            val preInitialBean = temp.preInitialBean
            if (!preInitialBean!!.correct) {
                var error = ErrorBean()
                error.soundType = preInitialBean.soundType
                error.soundInitial = preInitialBean.soundInitial
                error.soundPath = preInitialBean.soundPath
                error.tongueTwister = preInitialBean.tongueTwister
                errors.add(error)
            }
            temp = preInitialBean
        }
        materialDialog.show()
        if (errors.isNotEmpty()) {
            mPresenter?.jumpNoPass(errors)
        } else {
            mPresenter?.jumpPass()
        }
    }

    override fun jumpNoPass(errors: ArrayList<ErrorBean>) {
        materialDialog.dismiss()
        val intent = Intent(this, NoPassActivity::class.java)
        intent.putParcelableArrayListExtra("data", errors)
        startActivity(intent)
    }

    override fun jumpPass() {
        materialDialog.dismiss()
        startActivity(Intent(this, PassActivity::class.java))
    }

    override fun recordFinish(voicePath: String) {
        speechDialog.dismiss()
        setEnableClick(true)
        currentInitialBean.soundPath = voicePath
    }

    override fun showQuestions(linkedInitialBean: LinkedInitialBean) {
        this.currentInitialBean = linkedInitialBean
        setCurrentData()
    }

    private fun setCurrentData() {
        tvTitle.text = String.format(getString(R.string.test_tips), currentInitialBean.soundType)
        tvSoundInitial.text = currentInitialBean.soundInitial
        val split = currentInitialBean.soundWords.split("\\s+".toRegex())
        if (!split.isNullOrEmpty() && split.size >= 2) {
            tvSoundWords1.text = split[0]
            tvSoundWords2.text = split[1]
        }
    }

    private fun initSpeechSdk() {
        mSpeechSynthesizer?.let {
            val appId = getKoin().getProperty("appId")
            val appKey = getKoin().getProperty("appKey")
            val secretKey = getKoin().getProperty("secretKey")
            it.setSpeechSynthesizerListener(this)
            it.setContext(this)
            it.setAppId(appId)
            it.setApiKey(appKey, secretKey)
            it.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0") // 设置发声的人声音，普通女声
            it.initTts(TtsMode.ONLINE); // 初始化在线模式
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mSpeechSynthesizer?.release()
        mSpeechSynthesizer = null
    }

    override fun onSpeechFinish(p0: String) {
        LogUtils.i(p0)
        mPresenter?.playDiVoice()
    }

    override fun playDiCompletion() {
        speechDialog.show()
        mPresenter?.recordVoice()
    }

    private fun setEnableClick(Clickable: Boolean) {
        ivUp.isClickable = Clickable
        ivLeft.isClickable = Clickable
        ivStart.isClickable = Clickable
        ivRight.isClickable = Clickable
        ivDown.isClickable = Clickable
    }
}
